import path from 'path'
import os from 'os'
import { getServerConfig } from '../dao/ipAddresses'
import { getEffectiveAssetPaths } from '../dao/assetPaths'

const isDev = process.env.NODE_ENV === 'development'
const isWin = process.platform === 'win32'

// 默认配置
const DEFAULT_BASE_URL = 'http://192.168.0.151'
const DEFAULT_KPOP_BASE_URL = 'http://192.168.0.151'
const DEFAULT_BASE_URL_WITH_PORT = 'http://192.168.0.151:2000'
const DEFAULT_BASE_FACE2FACE = '8383'
const DEFAULT_BASE_TTS = '18180'
// 默认资源路径
const DEFAULT_ASSET_PATHS = {
  model: isWin
    ? path.join('\\\\Fw\\d', 'heygem_data', 'face2face', 'temp') // 模特视频
    : path.join('/www/wwwroot/files.flyingwaves.co', 'face2face', 'temp'),
  ttsProduct: isWin
    ? path.join('\\\\Fw\\d', 'heygem_data', 'face2face', 'temp') // TTS 产物
    : path.join('/www/wwwroot/files.flyingwaves.co', 'face2face', 'temp'),
  ttsRoot: isWin
    ? path.join('\\\\Fw\\d', 'heygem_data', 'voice', 'data') // TTS服务根目录
    : path.join('/www/wwwroot/files.flyingwaves.co', 'voice', 'data'),
  ttsTrain: isWin
    ? path.join('\\\\Fw\\d', 'heygem_data', 'voice', 'data', 'origin_audio') // TTS 训练产物
    : path.join('/www/wwwroot/files.flyingwaves.co', 'voice', 'data', 'origin_audio')
};

// 配置管理器类
class ConfigManager {
  constructor() {
    // 初始化状态
    this._initialized = false;
    this._initializing = null;

    // 初始默认配置
    this._serviceConfig = {
      face2face: `${DEFAULT_BASE_URL}:${DEFAULT_BASE_FACE2FACE}/easy`,
      tts: `${DEFAULT_BASE_URL}:${DEFAULT_BASE_TTS}`,
      baseUrl: DEFAULT_BASE_URL,
      kpopBaseUrl: DEFAULT_KPOP_BASE_URL,
      baseUrlWithPort: DEFAULT_BASE_URL_WITH_PORT
    };

    // 初始默认资源路径
    this._assetPaths = { ...DEFAULT_ASSET_PATHS };

    // 自动启动初始化
    this.initialize().catch(err => console.error('配置管理器初始化失败:', err));
  }

  // 初始化方法
  async initialize() {
    if (this._initialized) return;

    if (!this._initializing) {
      this._initializing = (async () => {
        try {
          // 获取服务URL配置
          const serviceUrls = await getServiceUrls();
          this._serviceConfig = serviceUrls;

          // 获取资源路径配置
          try {
            const paths = await getEffectiveAssetPaths();
            if (paths && Object.keys(paths).length > 0) {
              this._assetPaths = paths;
            }
          } catch (pathErr) {
            console.error('初始化资源路径失败，使用默认配置:', pathErr);
          }

          this._initialized = true;
        } catch (err) {
          console.error('初始化配置失败:', err);
        } finally {
          this._initializing = null;
        }
      })();
    }

    return this._initializing;
  }

  // 获取服务URL配置
  get serviceConfig() {
    return this._serviceConfig;
  }

  // 获取特定服务URL
  getServiceUrl(key) {
    return this._serviceConfig[key];
  }

  // 获取资源路径配置
  get assetPaths() {
    return this._assetPaths;
  }

  // 获取特定资源路径
  getAssetPath(key) {
    return this._assetPaths[key] || DEFAULT_ASSET_PATHS[key];
  }

  // 重新加载配置
  async reload() {
    try {
      // 重新获取服务URL配置
      this._serviceConfig = await getServiceUrls();

      // 重新获取资源路径配置
      const paths = await getEffectiveAssetPaths();
      if (paths && Object.keys(paths).length > 0) {
        this._assetPaths = paths;
      }

      return {
        serviceConfig: this._serviceConfig,
        assetPaths: this._assetPaths
      };
    } catch (err) {
      console.error('重新加载配置失败:', err);
      throw err;
    }
  }
}

// 原始getServiceUrls函数，保持不变
async function getServiceUrls() {
  try {
    // 从数据库获取配置
    const config = await getServerConfig()
    const baseUrl = config?.base_url || DEFAULT_BASE_URL
    const kpopBaseUrl = config?.kpop_baseUrl || DEFAULT_KPOP_BASE_URL
    const baseUrlWithPort = config?.base_url_with_port || DEFAULT_BASE_URL_WITH_PORT
    const face2face = config?.face2face || DEFAULT_BASE_FACE2FACE
    const tts = config?.tts || DEFAULT_BASE_TTS

    return {
      face2face: `${baseUrl}:${face2face}/easy`,
      tts: `${baseUrl}:${tts}`,
      baseUrl: baseUrl,
      kpopBaseUrl: kpopBaseUrl,
      baseUrlWithPort: baseUrlWithPort
    }
  } catch (error) {
    console.error('获取服务器配置失败，使用默认配置:', error)
    // 返回默认配置
    return {
      face2face: `${DEFAULT_BASE_URL}:${DEFAULT_BASE_FACE2FACE}/easy`,
      tts: `${DEFAULT_BASE_URL}:${DEFAULT_BASE_TTS}`,
      baseUrl: DEFAULT_BASE_URL,
      kpopBaseUrl: DEFAULT_KPOP_BASE_URL,
      baseUrlWithPort: DEFAULT_BASE_URL_WITH_PORT
    }
  }
}

// 创建配置管理器单例
const configManager = new ConfigManager();

// 导出配置方法
export const serviceUrl = new Proxy({}, {
  get: (target, prop) => {
    return configManager.getServiceUrl(prop);
  }
});

export const assetPath = new Proxy({}, {
  get: (target, prop) => {
    return configManager.getAssetPath(prop);
  }
});

// 导出重新加载配置方法
export async function reloadConfig() {
  return await configManager.reload();
}

// 导出确保配置初始化的方法
export async function ensureConfigInitialized() {
  return await configManager.initialize();
}

// 提供额外的直接访问方法
export function getServiceUrlConfig() {
  return configManager.serviceConfig;
}

export function getAssetPathConfig() {
  return configManager.assetPaths;
}
